package com.qidian.client;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

/**
 * 将转发平台获取的答案发送给360
 * 
 * */
public class ThreadSendAnswer  extends Thread
{
	static Logger logger = Logger.getLogger(ThreadSendAnswer.class) ;
	static TransMessageBeanCache tMsgCache = TransMessageBeanCache.getInstance() ;
    protected boolean      isStopped    = false;
    protected Thread       runningThread= null;
    long clientId ;
    String password ;
    
    public ThreadSendAnswer(long clientId, String password)
    {
    	this.clientId = clientId ;
    	this.password = password ;
    }
	
	public void run()
	{
        synchronized(this){
            this.runningThread = Thread.currentThread();
        }
        System.out.println(this.getClass().getName() + " start up") ;
        
		GetMethod httpGet  = null ;
		String url = TransConstants.serverURL+"/client" ;

		
		while(!isStopped)
		{

			TransMessageBean msg = tMsgCache.pollAnswered() ;
			if (msg == null)
			{
				try 
				{
					Thread.sleep(500) ;
				}
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
				continue ;
			}

			String answer = msg.getAnswer() ;
			try {
				answer = URLEncoder.encode(answer, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
				logger.error("发送答案失败:"+e1.getMessage()+"\n"+msg);
				continue ;
			}

			// 循环发送4次
			int i = 0 ; 
			while(i++ < 5)
			{
				httpGet = new GetMethod(url) ;
				httpGet.addRequestHeader("Content-type" , "text/html; charset=utf-8");
				httpGet.getParams().setContentCharset("UTF-8") ;
				int res = HttpStatus.SC_OK;
				try {
	
					NameValuePair[] params = new NameValuePair[6] ;
					params[0] = new NameValuePair("msgId",msg.getId()) ;
					params[1] = new NameValuePair("answer",URLEncoder.encode(msg.getAnswer(),"UTF-8")) ;
					params[2] = new NameValuePair("actionType","sendAnswer") ;
					params[3] = new NameValuePair("clientId",String.valueOf(clientId)) ;
					params[4] = new NameValuePair("password",password) ;
					params[5] = new NameValuePair("_",String.valueOf(System.currentTimeMillis())) ;
					
					
					httpGet.setQueryString(params) ;
					
					res = TransConstants.client.executeMethod(httpGet);
					if (res != HttpStatus.SC_OK)
					{
						logger.error("发送答案失败,状态码:"+res+"\n"+msg) ;
						continue ;
					}
					String rtn = httpGet.getResponseBodyAsString() ;
					if (!"0".equals(rtn))
						logger.error("发送答案失败:"+rtn+"\n"+msg) ;
					else
					{
						msg.setSendAnswerTime(System.currentTimeMillis()) ;
						logger.info("发送答案"+msg) ;
						File file = new File(msg.getFilePath()) ;
						file.delete() ;
						break ;
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("发送消息异常:"+e.getMessage()+"\n"+msg) ;
				} 
				finally{
					if (httpGet != null)
						httpGet.releaseConnection() ;
				}
				
				try {
					Thread.sleep(100) ;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}				
			}
			
			try {
				Thread.sleep(500) ;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		logger.info("Send answer thread stopped!");

	}
}
